package com.ruoyi.user.verification;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.PhoneUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.mapper.SysUserMapper;

/**
 * 登录验证
 *
 * @author mrj
 */
public class LoginVerification {

    private final static SysUserMapper sysUserMapper = SpringUtil.getBean(SysUserMapper.class);
    private final static RedisCache redisCache = SpringUtil.getBean(RedisCache.class);

    public static String login(String username, String password, String code, String userType) {
        String msg = "登录成功";
        if (StringUtils.isEmpty(username)) {
            msg = "用户名不能为空";
        }
        if (!PhoneUtil.isPhone(username)) {
            msg = "用户名不合法";
        }
        if (StringUtils.isNotBlank(code)) {
            String oldCode = redisCache.getCacheObject(CacheConstants.USER_NAME_CODE_KEY + username);
            if (StringUtils.isBlank(oldCode)) {
                msg = "验证码已过期";
            }
            if (!code.equals(oldCode)) {
                msg = "验证码错误";
            }
        } else {
            if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                    || username.length() > UserConstants.USERNAME_MAX_LENGTH) {
                msg = "账户长度必须在2到20个字符之间";
            } else if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                    || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
                msg = "密码长度必须在5到20个字符之间";
            }
            SysUser sysUser = sysUserMapper.selectUserByUserName(username, userType);
            if (ObjectUtil.isNull(sysUser)) {
                msg = MessageUtils.message("user.password.not.match");
            } else if (!SecurityUtils.matchesPassword(sysUser.getPassword(), password)) {
                msg = MessageUtils.message("user.not.exists");
            }
        }
        return msg;
    }
}
